package com.yjCar.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yjCar.mapper.RightsMapper;
import com.yjCar.pojo.Rights;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RightsServiceImpl implements RightsService{
    @Autowired
    private RightsMapper rightsMapper;
    @Override
    public List<Rights> getRightsList() {
        QueryWrapper queryWrapper = new QueryWrapper();
        List<Rights> data = rightsMapper.selectList(queryWrapper);

        //定义新的list
        List<Rights> categoriesList = new ArrayList<>();
        //先找到所有的一级分类
        for(Rights category : data){
            // 一级菜单的parentId是0
            if(category.getParentId() == 0){
                categoriesList.add(category);
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for(Rights category : categoriesList){
            category.setChildren(getChilde(category.getId(), data));
        }

        return categoriesList;

    }

    /**
     * 递归查找子菜单
     *
     * @param id 当前菜单id
     * @param rootList 要查找的列表
     * @return
     */
    private List<Rights> getChilde(Integer id, List<Rights> rootList){
        //子菜单
        List<Rights> childList = new ArrayList<>();
        for(Rights category : rootList){
            // 遍历所有节点，将父菜单id与传过来的id比较
            if(category.getParentId().equals(id)){
                childList.add(category);
            }
        }
        // 把子菜单的子菜单再循环一遍
        for(Rights category : childList){
            category.setChildren(getChilde(category.getId(), rootList));
        }
        // 递归退出条件
        if (childList.size() == 0){
            return null;
        }
        return childList;
    }

}
